use actix_web::{web, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

use crate::modules::web::database::Database;

// 登录请求数据结构
#[derive(Debug, Deserialize)]
pub struct LoginRequest {
    username: String,
    password: String,
}

// 登录响应数据结构
#[derive(Debug, Serialize)]
pub struct LoginResponse {
    success: bool,
    message: String,
    user_info: Option<UserInfo>,
}

// 用户信息数据结构
#[derive(Debug, Serialize)]
pub struct UserInfo {
    id: i32,
    username: String,
    email: String,
}

// 处理登录请求
pub async fn login(
    login_data: web::Json<LoginRequest>,
    db: web::Data<Arc<Database>>,
) -> impl Responder {
    let username = &login_data.username;
    let password = &login_data.password;
    
    // 验证用户凭据
    match db.validate_user(username, password) {
        Ok(is_valid) => {
            if is_valid {
                // 获取用户信息
                match db.get_user_info(username) {
                    Ok(Some((id, username, email))) => {
                        let response = LoginResponse {
                            success: true,
                            message: "登录成功".to_string(),
                            user_info: Some(UserInfo {
                                id,
                                username,
                                email,
                            }),
                        };
                        
                        match serde_json::to_string(&response) {
                            Ok(_json) => HttpResponse::Ok().json(response),
                            Err(_) => HttpResponse::InternalServerError().finish(),
                        }
                    },
                    _ => {
                        let response = LoginResponse {
                            success: false,
                            message: "获取用户信息失败".to_string(),
                            user_info: None,
                        };
                        
                        HttpResponse::Ok().json(response)
                    },
                }
            } else {
                let response = LoginResponse {
                    success: false,
                    message: "用户名或密码错误".to_string(),
                    user_info: None,
                };
                
                HttpResponse::Ok().json(response)
            }
        },
        Err(_) => {
            let response = LoginResponse {
                success: false,
                message: "数据库错误".to_string(),
                user_info: None,
            };
            
            HttpResponse::Ok().json(response)
        },
    }
}

// 健康检查端点（用于测试服务是否正常运行）
pub async fn health_check() -> impl Responder {
    HttpResponse::Ok().json(serde_json::json!({"status": "ok"}))
}